import json

import xlrd
from django.db import transaction
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.views.generic import RedirectView
from rest_framework.generics import ListAPIView, CreateAPIView, GenericAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from store.models import StoreManagement
from torts.models import Torts
from torts.serializers import TortListSerializer, TortAddSerializer, UpdateTortInfoSerializer
from users.models import User


class StandardPageNumberPagination(PageNumberPagination):
    page_size = 10
    page_size_query_description = 'page_size'
    max_page_size = 100


class TortViewSet(ModelViewSet):
    serializer_class = TortListSerializer

    def list(self, request, *args, **kwargs):
        return Response("helloworld")


class TortUpload(APIView):
    """导入侵权商品列表"""
    def post(self, request):
        json_data = request.POST.get('user_id')
        if not json_data:
            return Response({'error_msg': '缺少参数user_id'})
        user_id = int(json_data)

        # 接收文件
        f = request.FILES['tortfile']
        type_excel = f.name.split('.')[1]
        if type_excel == 'xls':
            wb = xlrd.open_workbook(filename=None, file_contents=f.read())
            table = wb.sheets()[0]
            nrows = table.nrows   # 获取行数
            ncole = table.ncols
            print(nrows, ncole)

            try:
                with transaction.atomic():
                    for i in range(1, nrows):
                        row_values = table.row_values(i)
                        print("*******")
                        user = User.objects.get(id=user_id)
                        tort = Torts.objects.create(staff=user, tort_company_ip=row_values[0], tort_asin=row_values[1],
                                                    old_asin=row_values[2], tort_content=row_values[3], deal_with_tort=row_values[4],
                                                    tort_image_url=row_values[5],)
            except Exception as e:
                return Response({"error_msg": str(e)})

        else:
            return Response({'error_msg': '文件类型不是xls'})

        return Response({'success_msg': '导入成功'})


class TortListView(ListAPIView):
    """侵权列表展示"""
    queryset = Torts.objects.all()
    serializer_class = TortListSerializer
    pagination_class = StandardPageNumberPagination


class TortAddView(CreateAPIView):
    """新增侵权商品"""
    serializer_class = TortAddSerializer


class TortUpdateView(GenericAPIView):
    """更新侵权商品"""
    queryset = Torts.objects.all()
    serializer_class = UpdateTortInfoSerializer

    def post(self, request):
        serializer = UpdateTortInfoSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        tort_id = request.POST.get('id')
        try:
            tort_info = Torts.objects.get(id=tort_id)
        except Exception as e:
            data = {"error_message": str(e)}
            return Response(data)
        try:
            user = User.objects.get(id=serializer.data['staff'])
        except Exception as e:
            return Response({"error_message": str(e)})

        tort_info.staff = user
        tort_info.tort_content = serializer.data['tort_content']
        tort_info.tort_company = serializer.data['tort_company']
        tort_info.tort_asin = serializer.data['tort_asin']
        tort_info.old_asin = serializer.data['old_asin']
        tort_info.tort_image_url = serializer.data['tort_image_url']
        tort_info.deal_with_tort = serializer.data['deal_with_tort']
        tort_info.save()

        return Response({"success_msg": "修改成功"})


class TortDeleteView(GenericAPIView):
    """删除侵权商品"""
    def post(self, request):

        post_data = request.body.decode()  # 取body值
        print(post_data, type(post_data))
        post_data = json.loads(post_data)  # 转化为djct
        print(post_data['id'])

        id_list = []
        for i in post_data['id']:
            print(i)
            id_list.append(int(i))
        try:
            purchase = Torts.objects.filter(id__in=id_list)
        except Exception as e:
            return Response({"error_msg": str(e)})
        if purchase:
            purchase.delete()
        else:
            return Response({"error_msg": "侵权物品不存在"})
        return Response({'success_msg': 'delete success'})

def external_privacy_policy(request):
    # 1.获取模板
    template = loader.get_template('ExternalPrivacyPolicy.html')


    # 2.渲染模板
    return HttpResponse(template.render())



class TestView(RedirectView):
    url = 'http://baidu.com/'



